package com.quanyan.user.service.impl;

import com.lefu.commons.utils.Page;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.comment.constants.UserCenterConstants;
import com.quanyan.comment.reqeust.ReqUserCollect;
import com.quanyan.comment.reqeust.ReqUserCollectQuery;
import com.quanyan.comment.response.RespUserCollect;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.user.mapper.TbUserCollectMapper;
import com.quanyan.user.mapper.UserCollectMapper;
import com.quanyan.user.model.db.TbUserCollect;
import com.quanyan.user.model.db.TbUserCollectExample;
import com.quanyan.user.service.UserCollectService;
import com.quanyan.user.utils.ValidUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Administrator on 2016/7/12.
 */
@Service
public class UserCollectServiceImpl implements UserCollectService {

    private static final Logger logger = LoggerFactory.getLogger(UserCollectServiceImpl.class);

    @Autowired
    private TbUserCollectMapper tbUserCollectMapper;

    @Autowired
    private UserCollectMapper userCollectMapper;

    @Override
    public APIResponse userCollect(ReqUserCollect reqUserCollect) {
        logger.info("start 用户收藏：{}",reqUserCollect.toString());
        //验证参数
        ValidUtils<ReqUserCollect> v = new ValidUtils<ReqUserCollect>();
        List<String> lstErrorMsg = v.getListMessage(reqUserCollect);
        if(CollectionUtils.isNotEmpty(lstErrorMsg))
            return APIResponse.returnFail(lstErrorMsg, ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        //查询用户是否已经收藏过
        TbUserCollectExample example = new TbUserCollectExample();
        TbUserCollectExample.Criteria c = example.createCriteria();
        c.andSystemCodeEqualTo(reqUserCollect.getSystemCode());
        c.andBusinessCodeEqualTo(reqUserCollect.getBusinessCode());
        c.andBussinessIdEqualTo(reqUserCollect.getBusinessId());
        c.andUserIdEqualTo(reqUserCollect.getUserId());
        try {
            List<TbUserCollect> lst = tbUserCollectMapper.selectByExample(example);
            if(lst != null && lst.size() > 0){
                TbUserCollect tbUserCollect = lst.get(0);
                if(tbUserCollect != null){
                    if(tbUserCollect.getStatus()== UserCenterConstants.Status.ABLE.byteValue()){
                        logger.info("start 用户收藏：{}", reqUserCollect.toString());
                        return  APIResponse.returnSuccess("用户已经收藏了！");
                    }//已收藏
                    else if(tbUserCollect.getStatus() == UserCenterConstants.Status.DISABLE.byteValue()){//曾经收藏 但是取消了
                        userCollectMapper.updateStatus(reqUserCollect.toMap());
                        logger.info("end 用户收藏：{}");
                        return APIResponse.returnSuccess();
                    }
                }
            }

            TbUserCollect userCollect = new TbUserCollect();
            userCollect.setSystemCode(reqUserCollect.getSystemCode());
            userCollect.setBusinessCode(reqUserCollect.getBusinessCode());
            userCollect.setBussinessId(reqUserCollect.getBusinessId());
            userCollect.setUserId(reqUserCollect.getUserId());
            userCollect.setStatus(reqUserCollect.getStatus().byteValue());
            userCollect.setCreateTime(new Date());
            userCollect.setUpdateTime(new Date());
            tbUserCollectMapper.insertSelective(userCollect);
            logger.info("end 用户收藏");
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("用户收藏异常：{}，exception:{}",reqUserCollect.toString(),e);
            return APIResponse.returnFail("系统异常!");
        }

    }

    @Override
    public APIResponse cancelUserCollect(ReqUserCollect reqUserCollect) {
        logger.info("start 用户取消收藏：{}",reqUserCollect.toString());
        //验证参数
        ValidUtils<ReqUserCollect> v = new ValidUtils<ReqUserCollect>();
        List<String> lstErrorMsg = v.getListMessage(reqUserCollect);
        if(CollectionUtils.isNotEmpty(lstErrorMsg))
            return APIResponse.returnFail(lstErrorMsg, ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);

        try {
            userCollectMapper.updateStatus(reqUserCollect.toMap());
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("用户取消收藏异常：{}，exception:{}", reqUserCollect.toString(), e);
            return APIResponse.returnFail("系统异常!");
        }

    }

    public APIResponse<PageObj<List<RespUserCollect>>> queryUserCollectOld(ReqUserCollectQuery reqUserCollectQuery) {
        logger.info("获取用户：{}的收藏",reqUserCollectQuery.toString());
        if(reqUserCollectQuery.getUserId() == null )
            return APIResponse.returnFail("userId不能为空");
        Page<ReqUserCollect> page = new Page<ReqUserCollect> ();
        page.setCurrentPage(reqUserCollectQuery.getPageNum());
        page.setShowCount(reqUserCollectQuery.getPageSize());
        try {
            List<RespUserCollect> lstUserCollect = userCollectMapper.findAllUserCollect(page,reqUserCollectQuery.toMap());
            logger.info("end query user collect result : ",lstUserCollect.toString());
            PageObj<List<RespUserCollect>> result = PageObj.create(page.getTotalResult(), page.getCurrentPage(), page.getShowCount(), lstUserCollect);
            return  APIResponse.returnSuccess(result);
        } catch (Exception e) {
            logger.error("获取用户：{}收藏失败：{}",reqUserCollectQuery.toString(),e);
            return APIResponse.returnFail("系统异常");
        }

    }

    @Override
    public APIResponse<PageObj<List<RespUserCollect>>> queryUserCollect(ReqUserCollectQuery reqUserCollectQuery){
        logger.info("获取用户：{}的收藏",reqUserCollectQuery.toString());
        if(reqUserCollectQuery.getUserId() == null )
            return APIResponse.returnFail("userId不能为空");

        TbUserCollectExample tbUserCollectExample = new TbUserCollectExample();
        TbUserCollectExample.Criteria criteria = tbUserCollectExample.createCriteria();
        criteria.andSystemCodeEqualTo(reqUserCollectQuery.getSystemCode());
        criteria.andBusinessCodeEqualTo(reqUserCollectQuery.getBusinessCode());
        criteria.andUserIdEqualTo(reqUserCollectQuery.getUserId());
        criteria.andStatusEqualTo(Constants.IS_ENABLE_TRUE);

        int total = tbUserCollectMapper.countByExample(tbUserCollectExample);
        int pageNum = reqUserCollectQuery.getPageNum();
        int pageSize = reqUserCollectQuery.getPageSize();

        tbUserCollectExample.setOrderByClause(" create_time desc");
        tbUserCollectExample.setPage(com.quanyan.common.Plugin.Page.createPage(total, pageNum, pageSize));
        List<TbUserCollect> lst = tbUserCollectMapper.selectByExample(tbUserCollectExample);
        List<RespUserCollect> lstRespUserCollect = null;
        if(lst != null && lst.size() > 0 ){
            lstRespUserCollect = new ArrayList<RespUserCollect>();
            for(TbUserCollect uc: lst){
                RespUserCollect r = new RespUserCollect();
                r.setSystemCode(uc.getSystemCode());
                r.setBusinessCode(uc.getBusinessCode());
                r.setBusinessId(uc.getBussinessId().toString());
                r.setCollectDate(uc.getCreateTime());
                r.setUserId(uc.getUserId());
                lstRespUserCollect.add(r);
            }
            logger.info("用户收藏{}：",lst.toString());
        }
        logger.info("结束活动查询{}",lstRespUserCollect == null?"":lstRespUserCollect.toString());
        PageObj<List<RespUserCollect>> result = PageObj.create(total, pageNum, pageSize, lstRespUserCollect);
        return APIResponse.returnSuccess(result);
    }



    public PageObj<List<RespUserCollect>> queryActivityCollect(ReqUserCollectQuery reqUserCollectQuery){
        if(reqUserCollectQuery.getUserId() == null)
            return null;
        logger.info("开始查询活动收藏====================》");
        Map<String ,Object> map = new HashMap<String, Object>();
        map.put("c_systemCode",Constants.ACTIVITY_SYSTEM_CODE);//活动系统
        map.put("c_businessCode",Constants.CLUB_COLLECT_ACTIVITY_BUSINESS_CODE);//俱乐部业务编码
        map.put("o_systemCode",Constants.SYSTEM_OUTDOOR);//户外系统
        map.put("o_businessCode",Constants.BUSINESS_OUTDOOR_CM);//户外活动
        map.put("uid",reqUserCollectQuery.getUserId());
        Page<ReqUserCollect> page = new Page<ReqUserCollect> ();
        int pageIndex = reqUserCollectQuery.getPageNum() + 1;
        page.setCurrentPage(pageIndex);
        page.setShowCount(reqUserCollectQuery.getPageSize());
        List<RespUserCollect> lstUserCollect = userCollectMapper.findAllActivityCollect(page,map);
        if(pageIndex > page.getTotalPage()){
            lstUserCollect = new ArrayList<RespUserCollect>();
            page.setTotalPage(0);
            page.setTotalResult(0);
        }
        PageObj<List<RespUserCollect>> result = PageObj.create(page.getTotalResult(), page.getCurrentPage(), page.getShowCount(), lstUserCollect);
        logger.info("结束查询活动收藏：{}",lstUserCollect.toString());
        return  result;
    }


        @Override
    public APIResponse<PageObj<List<Integer>>> queryUsersByBusiness(ReqUserCollectQuery reqUserCollectQuery){

        if(reqUserCollectQuery == null)
            return APIResponse.returnFail("参数不能为空");

        if(StringUtils.isBlank(reqUserCollectQuery.getSystemCode()))
            return APIResponse.returnFail("systemCode不能为空！");

        if(StringUtils.isBlank(reqUserCollectQuery.getBusinessCode()))
            return APIResponse.returnFail("businessCode不能为空！");

        if( reqUserCollectQuery.getBusinessId() == null)
            return APIResponse.returnFail("businessId不能为空！");
        logger.info("start find 系统业务有多少用户收藏 ：{}",reqUserCollectQuery.toString());

        Page page = new Page();
        page.setCurrentPage(reqUserCollectQuery.getPageNum());
        page.setShowCount(reqUserCollectQuery.getPageSize());
        List<Integer> listUserId = userCollectMapper.findAllUsersByBusiness(page, reqUserCollectQuery.toMap());
        logger.info("end 系统业务有多少用户收藏  listUserId : {}",listUserId.toString());
        PageObj<List<Integer>> result = PageObj.create(page.getTotalResult(), page.getCurrentPage(), page.getShowCount(), listUserId);
        return APIResponse.returnSuccess(result);
    }


    @Override
    public APIResponse<Boolean> isUserCollect(ReqUserCollectQuery reqUserCollect) {
        if(reqUserCollect == null)
            return APIResponse.returnFail("参数不能为空");

        if(StringUtils.isBlank( reqUserCollect.getSystemCode()))
            return APIResponse.returnFail("systemCode不能为空！");

        if(StringUtils.isBlank(reqUserCollect.getBusinessCode()))
            return APIResponse.returnFail("businessCode不能为空！");

        if( reqUserCollect.getBusinessId() == null)
            return APIResponse.returnFail("businessId不能为空！");

        if( reqUserCollect.getUserId() == null)
            return APIResponse.returnFail("userId不能为空！");


        logger.info("start check 用户收藏：{}", reqUserCollect.toString());
        TbUserCollectExample example = new TbUserCollectExample();
        TbUserCollectExample.Criteria c = example.createCriteria();
        c.andSystemCodeEqualTo(reqUserCollect.getSystemCode());
        c.andBusinessCodeEqualTo(reqUserCollect.getBusinessCode());
        c.andBussinessIdEqualTo(reqUserCollect.getBusinessId());
        c.andUserIdEqualTo(reqUserCollect.getUserId());

        boolean flag = true;
        List<TbUserCollect> lst = tbUserCollectMapper.selectByExample(example);
        if(lst == null || lst.size() < 1)
        return APIResponse.returnSuccess(true); //未收藏

        TbUserCollect tbUserCollect = lst.get(0);
        if(tbUserCollect.getStatus()== UserCenterConstants.Status.ABLE.byteValue())//已收藏
            return APIResponse.returnSuccess(false) ;//已收藏
        else //曾经收藏 但是取消
            return APIResponse.returnSuccess(true); //未收藏

    }


    public APIResponse cancelUserCollect(ReqUserCollect reqUserCollect,List<Integer> lstBusinessId) {
        reqUserCollect.setBusinessId(1);
        logger.info("start 用户取消收藏：{}", reqUserCollect.toString());
        //验证参数
        ValidUtils<ReqUserCollect> v = new ValidUtils<ReqUserCollect>();
        List<String> lstErrorMsg = v.getListMessage(reqUserCollect);
        if(CollectionUtils.isNotEmpty(lstErrorMsg))
            return APIResponse.returnFail(lstErrorMsg, ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);

        Map<String,Object> map = reqUserCollect.toMap();
        map.put("list",lstBusinessId);

        try {
            userCollectMapper.batchUpdateStatus(map);
            return APIResponse.returnSuccess();
        } catch (Exception e) {
            logger.error("用户取消收藏异常：{}，exception:{}", reqUserCollect.toString(), e);
            return APIResponse.returnFail("系统异常!");
        }


    }

}
